﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MarkDownFileSplitter.Markdown
{
    /// <summary>
    /// 一个Markdown文件，它由一个一级MarkdownFileContentItem组成
    /// 
    /// 通过传递一个本地文件，进行自驱动的解析
    /// </summary>
    internal class MarkdownFileContent
    {
        public List<MarkdownFileContentItem> RootItems { get; set; }
        public string[] ContentLines { get; set; }
        private string m_fileName;
        public EventHandler OnLoad;

        public MarkdownFileContent(string filePath)
        {
            m_fileName = filePath;
        }

        public void LoadFile()
        {
            string[] lines = File.ReadAllLines(m_fileName);
            List<string> allLines = new List<string>();
            allLines.AddRange(lines);
            for (var i = allLines.Count - 1; i >= 1; i--)
            {
                if (string.IsNullOrWhiteSpace(allLines[i]) && string.IsNullOrWhiteSpace(allLines[i - 1]))
                {
                    allLines.RemoveAt(i);
                }
            }
            if (lines.Length == 0)
            {
                return;
            }
            while (allLines.Count>0)
            {
                if (string.IsNullOrWhiteSpace(allLines[0]))
                {
                    allLines.RemoveAt(0);
                }
                else { break; }
            }
            if (allLines[0].Trim().StartsWith("#") == false)
            {
                allLines.Insert(0, "# " + Path.GetFileNameWithoutExtension(m_fileName));
            }
            ContentLines = allLines.ToArray();
            RootItems = ParseMarkdown(allLines.ToArray());

            if (OnLoad != null)
            {
                OnLoad(null, null);
            }
        }
        internal void LoadText(string[] text)
        {
            ContentLines = text;
            RootItems = ParseMarkdown(text.ToArray());

            if (OnLoad != null)
            {
                OnLoad(null, null);
            }
        }

        public List<MarkdownFileContentItem> ParseMarkdown(string[] lines)
        {
            List<MarkdownFileContentItem> rootItems = new List<MarkdownFileContentItem>();

            MarkdownFileContentItem currentLevel1 = null;
            MarkdownFileContentItem currentLevel2 = null;
            MarkdownFileContentItem currentLevel3 = null;

            for (int i = 0; i < lines.Length; i++)
            {
                string line = lines[i];
                if (line.StartsWith("### "))
                {
                    if (currentLevel3 != null)
                    {
                        currentLevel3.EndRowIndex = i-1;
                    }
                    currentLevel3 = new MarkdownFileContentItem(3, line, i, i);
                    if (currentLevel2 != null)
                    {
                        currentLevel2.Children.Add(currentLevel3);
                    }
                    else if (currentLevel1 != null)
                    {
                        currentLevel1.Children.Add(currentLevel3);
                    }
                    else
                    {
                        rootItems.Add(currentLevel3);
                    }
                }
                else if (line.StartsWith("## "))
                {
                    if (currentLevel2 != null)
                    {
                        currentLevel2.EndRowIndex = i - 1;
                    }
                    currentLevel2 = new MarkdownFileContentItem(2, line, i, i);
                    if (currentLevel1 != null)
                    {
                        currentLevel1.Children.Add(currentLevel2);
                    }
                    else
                    {
                        rootItems.Add(currentLevel2);
                    }
                }
                else if (line.StartsWith("# "))
                {
                    if (currentLevel1 != null)
                    {
                        currentLevel1.EndRowIndex = i - 1;
                    }
                    currentLevel1 = new MarkdownFileContentItem(1, line, i, i);
                    rootItems.Add(currentLevel1);
                }
            }
            //这里是介绍的部分
            if (currentLevel3 != null)
                currentLevel3.EndRowIndex = lines.Length;
            if (currentLevel2 != null)
                currentLevel2.EndRowIndex = lines.Length;
            if (currentLevel1 != null)
                currentLevel1.EndRowIndex = lines.Length;
            return rootItems;
        }

        internal void Save(string fileName)
        {
            if (fileName == null) fileName = m_fileName;
            File.WriteAllLines(fileName,ContentLines);

            MessageBox.Show("OK");
        }
        public string GetNextFileName()
        {
            var fileName = Path.GetFileNameWithoutExtension(m_fileName);
            int maxT = 0;
            var minFileName = "";
            for (var i = 2; i <= fileName.Length; i++)
            {
                var str = fileName.Substring(fileName.Length - i);
                if (int.TryParse(str, out int t))
                {
                    minFileName = fileName.Substring(0, fileName.Length - i);
                    maxT = t;
                }
            }
            var dir = Path.GetDirectoryName(m_fileName);
            maxT = 1;
            var nf = Path.Combine(dir, minFileName + maxT.ToString() + ".md");
            while (File.Exists(nf))
            {
                maxT++;
                nf = Path.Combine(dir, minFileName + maxT.ToString() + ".md");
            }
            return nf;
        }

        
    }
}
